<?php
	namespace app\index\controller;

	use \think\Db;

	class Reg extends Base{
		public function index(){
			try{
				if($this->method=='post'){
					$user=htmlspecialchars(input('post.user'));

					if($user==''){
						$this->json(['code'=>0,'msg'=>'请输入您的用户名']);
					}

					if(mb_strlen($user,'utf8')<6 || mb_strlen($user,'utf8')>10 ){
						$this->json(['code'=>0,'msg'=>'请输入6-10个字符的用户名']);
					}

					$pass=input('post.pass');

					if($pass==''){
						$this->json(['code'=>0,'msg'=>'请输入您的密码']);
					}

					if(mb_strlen($pass,'utf8')<9 || mb_strlen($pass,'utf8')>16 ){
						$this->json(['code'=>0,'msg'=>'请输入9-16个字符的密码']);
					}

					$re_pass=input('post.re_pass');

					if($re_pass==''){
						$this->json(['code'=>0,'msg'=>'请确认您的密码']);
					}

					if($pass!=$re_pass){
						$this->json(['code'=>0,'msg'=>'两次密码输入的不一致']);
					}

					$tel=input('post.tel');

					if($tel==''){
						$this->json(['code'=>0,'msg'=>'请输入您的号码']);
					}

					$patt='/^(1(([35789][0-9])|(47)))\d{8}$/';

					if(!preg_match($patt,$tel)){
						$this->json(['code'=>0,'msg'=>'请输入正确的号码']);
					}

					$email=input('post.email');

					if($email==''){
						$this->json(['code'=>0,'msg'=>'请输入您的邮箱']);
					}

					if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
						$this->json(['code'=>0,'msg'=>'请输入正确的邮箱']);
					}

					if(Db::name('user')->where(['u_username'=>$user])->find()){
						$this->json(['code'=>0,'msg'=>'该用户名已被注册']);
					}

					if(Db::name('user')->where(['u_tel'=>$tel])->find()){
						$this->json(['code'=>0,'msg'=>'该手机号已被注册']);
					}

					if(Db::name('user')->where(['u_email'=>$email])->find()){
						$this->json(['code'=>0,'msg'=>'该邮箱已被注册']);
					}

					$ip=$_SERVER['REMOTE_ADDR'];

					$time=time();

					$res=Db::name('user')->insertGetId(['u_username'=>$user,'u_userpwd'=>md5($pass),'u_tel'=>$tel,'u_email'=>$email,'u_createIp'=>$ip,'u_createTime'=>$time,'u_lastIp'=>$ip,'u_lastTime'=>$time]);

					if($res){

						$token=md5($res.$user.time().$this->key).$this->key;

						// 如果注册成功就将信息存入redis,生成token,实现自动登录
						$this->checkLogin(['u_id'=>$res,'u_username'=>$user,'u_userpwd'=>md5($pass),'u_icon'=>''],$token);

						$this->json(['msg'=>'注册成功','code'=>1,'token'=>$token]);
					}

					$this->json(['code'=>0,'msg'=>'注册失败']);
				}else{
					echo '拒绝访问';
				}
			}catch(\Exception $e){
				return $this->err($e);
			}
		}

		// 注册成功之后，把用户信息存入reids,实现自动登录
		private function checkLogin($arr=[],$token=''){

			$row=$this->redis->get('user:'.$arr['u_id']);

			$time=$this->time;


			if($row){
				$this->redis->del($row);
			}

			$this->redis->setex('user:'.$arr['u_id'],$time,$token);

			$this->redis->hmset($token,$arr);

			$this->redis->Expire($token,$time);
		}
	}
?>